package com.lei.chinese_herbal_medicine.Util;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lei.chinese_herbal_medicine.Entity.Model;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.*;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Component
public class HandleModelDataUtil {
    /***
     * 获取模型训练完毕后产生的数据
     * @return
     * @throws IOException
     */
    @Value("${model.project_path}")
    private String projectPath;
    @Value("${model.train_data_abs_path}")
    private String trainDataAbsPath;
    @Value("${model.model_application_abs_path}")
    private String model_application_abs_path;
    @Value("${model.train_dataset_dir_path}")

    private String train_dataset_dir_path;
    @Value("${model.test_dataset_dir_path}")
    private String test_dataset_dir_path;
    @Value("${model.newModel_path_dir}")
    private String newModelPathDir;
    @Value("${model.basicModel_path_dir}")
    private String basicModelPathDir;


    public Map getModelTrainData() throws IOException  {
        Map result=null;
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            File file = new File(projectPath+trainDataAbsPath);
            result = objectMapper.readValue(file,  Map.class);
            ArrayList accuracy_rate= (ArrayList) result.get("accuracy_rate");
            ArrayList loss_rate= (ArrayList) result.get("loss_rate");
            HashMap herb_accuracy_rate= (HashMap) result.get("herb_accuracy_rate");
            result.put("accuracy_rate",accuracy_rate);
            result.put("loss_rate",loss_rate);
            result.put("herb_accuracy_rate",herb_accuracy_rate);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    /***
     * 向python的application写入自定义模型数据
     * @param model model_file_name、batch_size、shuffle、layerOne、layerTwo、layerThree
     * @param map   species_number、is_new_model
     * @return
     */
    public boolean setModelApplication(Model model,Map map) throws IOException {
        Map result=null;
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            File file = new File(projectPath+model_application_abs_path);
            result = objectMapper.readValue(file,  Map.class);
            result.put("model_file_name",model.getModelName());
            result.put("batch_size",model.getBatchSize());
            result.put("shuffle","1".equals(model.getShuffle().trim()));
            result.put("species_number",map.get("species_number"));
            result.put("is_new_model",map.get("is_new_model"));
            result.put("newModelPathDir",newModelPathDir);
            result.put("basicModelPathDir",basicModelPathDir);
            result.put("train_dataset_dir_path",train_dataset_dir_path);
            result.put("test_dataset_dir_path",test_dataset_dir_path);
            result.put("basicModel_file_name",map.get("basicModel_file_name"));
            ArrayList layers= (ArrayList) result.get("layer");
            HashMap layerOne= (HashMap) layers.get(0);
            layerOne.put("learn_rate",model.getLayearOne().getLearnRate());
            layerOne.put("freeze_rate",model.getLayearOne().getFreezeRate());
            layerOne.put("attenuation_rate",model.getLayearOne().getAttenuationRate());
            layerOne.put("epoch",model.getLayearOne().getEpoch());
            HashMap layerTwo= (HashMap) layers.get(1);
            layerTwo.put("learn_rate",model.getLayearTwo().getLearnRate());
            layerTwo.put("freeze_rate",model.getLayearTwo().getFreezeRate());
            layerTwo.put("attenuation_rate",model.getLayearTwo().getAttenuationRate());
            layerTwo.put("epoch",model.getLayearTwo().getEpoch());
            HashMap layerThree= (HashMap) layers.get(2);
            layerThree.put("learn_rate",model.getLayearThree().getLearnRate());
            layerThree.put("freeze_rate",model.getLayearThree().getFreezeRate());
            layerThree.put("attenuation_rate",model.getLayearThree().getAttenuationRate());
            layerThree.put("epoch",model.getLayearThree().getEpoch());
            System.out.println(result);
            FileWriter fileWriter = new FileWriter(file);
            objectMapper.writeValue(fileWriter, result);
            fileWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return true;
    }
    /**
     * 以byte[]方式读取文件
     *
     * @param filePath 文件名
     * @return
     * @throws IOException
     */
    public static byte[] readFileByBytes(String filePath) throws IOException {
        try (InputStream in = new BufferedInputStream(new FileInputStream(filePath));
             ByteArrayOutputStream out = new ByteArrayOutputStream();) {
            byte[] tempbytes = new byte[in.available()];
            for (int i = 0; (i = in.read(tempbytes)) != -1;) {
                out.write(tempbytes, 0, i);
            }
            byte[] bytes=out.toByteArray();
            out.close();
            in.close();
            return bytes;
        }
    }
}
